package cn.sail.shop3.api.controller;
import cn.sail.shop3.api.dao.UserDao;
import cn.sail.shop3.api.dao.impl.UserDaoImpl;
import cn.sail.shop3.api.entity.User;
import javafx.scene.control.Alert;

import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;

@WebServlet("/register")
public class RegisterServlet extends BaseServlet {

    private UserDao userDao = new UserDaoImpl();

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String userName = req.getParameter("userName");
        String password = req.getParameter("password");

        User dbUser = new User();
        dbUser.setUserName(userName);
        dbUser.setPassword(password);
        User dbUser2 = new User();
        int user = 0;
        dbUser2 = userDao.selectByUserName(userName);
        System.out.println(dbUser2);
        if(null != dbUser2){
            errorResp(resp,"用户已存在，不能注册");
            return;
        }

        if(userName == "" && password == ""){
            errorResp(resp,"用户名和密码都不能为空");
            return;
        }
        if(userName == ""){
            errorResp(resp,"用户名不能为空");
            return;
        }
        if(password == ""){
            errorResp(resp,"密码不能为空");
            return;
        }

        user = userDao.insert(dbUser);
        resp.setHeader("Access-Control-Allow-Origin", "*");
        //返回用户信息
        successResp(resp, dbUser);

//        RequestDispatcher dispatcher = request.getRequestDispatcher("https://www.baidu.com/");
//        response.getWriter().print("中国你好");

//        if(user != 0){
//            resp.sendRedirect("/index.html");
//            System.out.println("123");
//        }else{
//            resp.sendRedirect("/register.html");
//        }

    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

}